package framework.jackson.custom;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;

/**
 * 自定义序列化器，序列化 InnerObj 时，忽略 g属性
 */
public class JsonSerializerTest {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {
        Obj.InnerObj innerObj = new Obj.InnerObj("value_g", "value_h");
        Obj obj = new Obj("value_a", innerObj, "value_c");

        SimpleModule module = new SimpleModule();
        module.addSerializer(Obj.InnerObj.class, new MyObjectSerializer());
        mapper.registerModule(module);

        // {"a":"value_a","b":{"h":"value_h"},"c":"value_c"}
        String result = mapper.writeValueAsString(obj);
        System.out.println(result);
    }

    public static class MyObjectSerializer extends JsonSerializer<Obj.InnerObj> {
        @Override
        public void serialize(Obj.InnerObj value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeStartObject();
            // 不序列化 InnerObj.g
            // gen.writeStringField("g", value.getG());
            gen.writeStringField("h", value.getH());
            gen.writeEndObject();
        }
    }
}
